package com.org.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.org.Msg.Msg;
import com.org.entity.User;
import com.org.mapper.UserMapper;
import com.org.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2020-12-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService,UserDetailsService {
    @Autowired
    UserMapper userMapper;

    /**
     * 实现UserDetailsService接口的方法，用于获取用户个人信息
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查找用户,相当于select * from user where username='${s}'
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",s);
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            throw new UsernameNotFoundException("用户名错误！！");
        }

        //获取用户权限，并把其添加到GrantedAuthority中
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(user.getRole());
        grantedAuthorities.add(grantedAuthority);

        return new org.springframework.security.core.userdetails.User(s,user.getPassword(),grantedAuthorities);
    }

    /**
     * 注册操作
     * @param user
     * @return
     */
    public Msg register(User user){
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));  //对密码进行加密

        //mybatis-plus的语法，相当于select * from user where username='${username}'
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        User user2=userMapper.selectOne(wrapper);
        try{
            if(user2!=null){
                //账号已被注册过了
                return Msg.fail("账号已被注册过了");
            }
            userMapper.insert(user);
            return Msg.success("注册成功！");
        }catch (Exception e){
            return Msg.fail(e.getLocalizedMessage());
        }

    }
}
